<template>
  <basic-container class="channelAdd">
    <el-form :inline="true" :model="channelAdd" class="demo-form-inline">
      <el-form-item label="渠道类别" style="margin-bottom: 15px!important;margin-left: 10px;">
          <el-select ref="channelTypeRef" v-model="getChannelList.parentId" clearable filterable size="medium" placeholder="渠道类别" style="width: 155px" >
            <el-option v-for="(channelItem,channel) in channelTypeList" :key="channel" :label="channelItem.channelName"
              :value="channelItem.id">
              <span :data-id="channelItem.id" style="display: inline-block;width: 150px;padding: 0 20px;margin-left: -20px;"
                @click="getChannelTypeId($event)">{{ channelItem.channelName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道" style="margin-bottom: 15px!important;">
          <el-select ref="channelRef" v-model="channelName" clearable filterable size="medium" placeholder="渠道" style="width: 155px" >
            <el-option v-for="(channelItem,channel) in channerList" :key="channel" :label="channelItem.channelName"
              :value="channelItem.channelName"></el-option>
          </el-select>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="onSearch" size="small">查询</el-button>
        <el-button type="success" plain @click="handleAddchannel" icon="el-icon-plus" size="small">新增</el-button>
        <el-form-item>
          <!-- <el-button type="danger" plain @click="" icon="el-icon-delete" size="small">删除</el-button> -->
        </el-form-item>
      </el-form-item>
    </el-form>

    <!-- <div class="channelAddcon">
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;"></div>
      <el-checkbox-group v-model="checkedchannel" @change="handleCheckedchannelChange">
        <el-checkbox v-for="item in channelList" :label="item.channelName" :key="item.id" border size='mini' style="margin-bottom: 10px;">{{item.channelName}}</el-checkbox>
      </el-checkbox-group>
    </div> -->
    <div class="channelAddcon">
      <el-table :data="channelList" border style="width: 100%">
        <el-table-column prop="id" label="渠道ID">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
        </el-table-column>
        <el-table-column prop="operator" label="创建人">
        </el-table-column>
        <el-table-column prop="channelName" label="渠道名称">
        </el-table-column>
        <el-table-column prop="cities" label="应用城市">
          <template slot-scope="{row}">
            <template v-if="row.cities">
              <el-tag class="mb-5 mr-5" v-for="(item, index) in row.cities.split(',')" :key="index">{{item}}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{row}">
            <el-button @click="onEditCity(row)" type="text">编辑城市</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="channelAdd.page" :limit.sync="channelAdd.size" layout="sizes,prev, pager, next,total"
        @pagination="getchannalList" />

    </div>
    <el-dialog title="新增渠道" :visible.sync="dialogFormVisible">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :label-width="formLabelWidth">

        <el-form-item label="渠道类别" style="margin-bottom: 15px!important "  prop="parentId">
          <el-select v-model="ruleForm.parentId" clearable filterable size="medium" placeholder="渠道类别" style="width: 155px" >
            <el-option v-for="(channelItem,channel) in channelTypeList" :key="channel" :label="channelItem.channelName"
              :value="channelItem.id">
              <span :data-id="channelItem.id" style="display: inline-block;width: 150px;padding: 0 20px;margin-left: -20px;"
                @click="getParentId($event)">{{ channelItem.channelName }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="渠道名称" prop="coninfo">
          <el-input v-model.trim="ruleForm.coninfo" clearable autocomplete="off" type="textarea" size="small" maxlength="200"
            show-word-limit :autosize="{ minRows: 8, maxRows:10}" @keydown.up.native="this.value=this.value.replace(/\s+/g,'')"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleAddchannelsumbit(ruleForm,'ruleForm')" size="small">提 交</el-button>
        <el-button @click="dialogFormVisible = false" size="small">取 消</el-button>
      </div>
    </el-dialog>

    <eidtCityDialog ref="eidtCityDialog" @edit="handleEditCity"></eidtCityDialog>
  </basic-container>
</template>

<script>
import {
  getOrderChannelList, // 渠道
  getOrderChannelTypeList // 渠道类别列表
} from "@/api/createOrder";
  import {
    addOrderChannel,
    getOrderChannelListProtFile
  } from "@/api/commodityfiles";
  import Pagination from "@/components/Pagination"; //分页
  import eidtCityDialog from './components/eidtCityDialog'
  export default {
    components: {
      Pagination,
      eidtCityDialog
    },
    data() {
      return {
        channelAdd: {
          page: 1,
          size: 10,
        },
        total: 2,
        ruleForm: {
          coninfo: '',
          parentId: ''
        },
        rules: {
          parentId: [{
            required: true,
            message: '请选择渠道类别',
            trigger: 'blur'
          }],
          coninfo: [{
            required: true,
            message: '请输入渠道内容',
            trigger: 'blur'
          }],
        },
        formLabelWidth: '120px',
        
        // isIndeterminate: true,
        // checkAll: false,
        // checkedCities: [],
        //  checkedchannel: [],
        channelList: [],
        dialogFormVisible: false,
        isflag: false,
        channelType: '',
        channel: '',
        channelName: '',
        channelTypeList: [], // 渠道类别列表
        channerList: [],
        getChannelList: { // 渠道列表
            parentId: ''
        },
      }
    },
    created() {
    },
    mounted() {
      this.getchannalList();
      // 渠道类别
      getOrderChannelTypeList().then(res => {
        this.channelTypeList = res.data.data;
      })
    },
    methods: {
    // 选择框回车失焦
    selectBlur(e) {
        if (e.keyCode == 13) {
            e.returnValue = false;
        }
    },
    // 新增渠道选择类型
    getParentId(e) {
      this.ruleForm.parentId = e.currentTarget.dataset.id;
    },
    // 选择渠道类型
    getChannelTypeId(e) {
      this.getChannelList.parentId = e.currentTarget.dataset.id;
      // 渠道列表接口
      getOrderChannelList(this.getChannelList).then(res => {
        this.channerList = []
        this.channelName  = ''
        let result = res.data.data;
        result.forEach(item => {
          this.channerList = result;
          if (this.channel !== undefined) {
            if (item.channelKey == this.channel) {
                this.channerList = result;
            } else {
                this.channerList = result;
                this.channel = '';
            }
          }
        })
      })
    },
      getchannalList() {
        const params = this.getParams()
        getOrderChannelListProtFile(params).then(response => {
          this.channelList = response.data.data.rows;
          this.total = response.data.data.total;
        });
      },
      handleChannelTypeId(data) {
        if (data) {
          this.getchannalList()
        }
      },
      
      onSearch() {
        // if(!this.getChannelList.parentId) {
        //     this.$message({
        //         type: "warning",
        //         message: '请先选择渠道类别'
        //     });
        //     return 
        // }
        this.getchannalList()
      },  
      getParams() {
        const params = {
          parentId: this.getChannelList.parentId || undefined,
          channelName: this.channelName || undefined,
          page: this.channelAdd.page,
          size: this.channelAdd.size
        }
        return params
      },
      handleAddchannel() {
        this.dialogFormVisible = true
      },
      handleAddchannelsumbit(item, formName) {
        this.$refs[formName].validate((valid) => {
          if(!this.ruleForm.parentId) {
            this.$message({
              type: "warning",
              message: '请选择渠道类别！'
            });
            return 
          }
          if (valid) {
            var name = JSON.stringify(item.coninfo),
              str = [],
              itemName = [],
              namerep = (name.replace(/"/g, "")).replace(/，/g, ',');
            str = namerep.split(',')
            console.log('namerep', namerep,typeof(namerep))
            str.forEach((channel, index) => {
              if (channel.length > 12) {
                this.$message({
                  type: "warning",
                  message: '渠道名称为' + channel + ';' + '第' + (index + 1) + '个不得超过12个字符!'
                });
                this.isflag = true;
                return false;
              } else {
                var newArr = [];
                var len = str.length;
                for (var i = 0; i < len; i++) {
                  if (newArr.indexOf(str[i]) == -1) {
                    newArr.push(str[i]);
                    this.isflag = false;
                  } else {
                    this.$message({
                      type: "warning",
                      message: '渠道名称不允许重复也不允许为空'
                    });
                    this.isflag = true;

                    return false;
                  }
                }
                return newArr;
              }

            })
            if (this.isflag == false) {
              const addOrderData = {
                parentId: this.ruleForm.parentId,
                channelName: (item.coninfo.replace(/"/g, "")).replace(/，/g, ','),
                type: 2
              }
              addOrderChannel(addOrderData).then(res => {
                if (res.data.code == 200) {
                  this.$message({
                    type: "success",
                    message: '渠道添加成功'
                  });
                  this.$refs[formName].resetFields();
                  this.dialogFormVisible = false;
                  setTimeout(() => {
                    this.getchannalList();
                  }, 1.5 * 1000);

                } else {
                  this.$message({
                    type: "warning",
                    message: '渠道添加失败'
                  });
                  this.$refs[formName].resetFields();
                }
              })
            }
          } else {
            this.$message({
              type: "warning",
              message: "请填写渠道名称!"
            });
            return false;
          }
        });

      },
      onEditCity(data) {
        this.$refs.eidtCityDialog.show(data)
        console.log(data)
      },
      handleEditCity() {
        this.getchannalList()
      }
    },
  };
</script>

<style scoped lang="scss">
  .channelAdd {

    .el-checkbox.is-bordered+.el-checkbox.is-bordered {
      margin-left: 0 !important;
    }
  }
</style>
